package me.zhengjie.modules.info.service.impl;

import me.zhengjie.modules.info.domain.Worker;
import me.zhengjie.utils.ValidationUtil;
import me.zhengjie.modules.info.repository.WorkerRepository;
import me.zhengjie.modules.info.service.WorkerService;
import me.zhengjie.modules.info.service.dto.WorkerDTO;
import me.zhengjie.modules.info.service.mapper.WorkerMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.util.Optional;

/**
* @author 张鹏
* @date 2019-05-09
*/
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class WorkerServiceImpl implements WorkerService {

    @Autowired
    private WorkerRepository workerRepository;

    @Autowired
    private WorkerMapper workerMapper;

    @Override
    public WorkerDTO findById(Long id) {
        Optional<Worker> worker = workerRepository.findById(id);
        ValidationUtil.isNull(worker,"Worker","id",id);
        return workerMapper.toDto(worker.get());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public WorkerDTO create(Worker resources) {
        return workerMapper.toDto(workerRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Worker resources) {
        Optional<Worker> optionalWorker = workerRepository.findById(resources.getId());
        ValidationUtil.isNull( optionalWorker,"Worker","id",resources.getId());

        Worker worker = optionalWorker.get();
        // 此处需自己修改
        resources.setId(worker.getId());
        workerRepository.save(resources);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long id) {
        workerRepository.deleteById(id);
    }
}